﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InitSaleInfoForm.aspx.cs"
    Inherits="PSS.WebSite.SaleManage.InitSaleInfoForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../lib/boot.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" method="post">
    <input name="InitSaleId" class="mini-hidden" />
    <fieldset style="border: solid 1px #aaa; padding: 5px;">
        <legend>单据信息</legend>
        <table align="left" style="table-layout: fixed; width: 100%;">
            <tr>
                <td style="width: 80px;" align="right">
                    销货单位：
                </td>
                <td style="width: 120px;" align="left">
                    <input name="CustomerId" class="mini-combobox" style="width: 120px;" valuefield="CustomerId"
                        textfield="CustomerName" required="true" />
                </td>
                <td style="width: 80px;" align="right">
                    单据日期：
                </td>
                <td style="width: 120px;" align="left">
                    <input name="DocDate" style="width: 120px;" class="mini-datepicker" format="yyyy-MM-dd"
                        required="true" />
                </td>
                <td style="width: 80px;" align="right">
                    单据编号：
                </td>
                <td style="width: 120px;" align="left">
                    <span id="SaleNumber" name="SaleNumber"></span>
                </td>
                <td style="width: 80px;" align="right">
                    业务类别：
                </td>
                <td style="width: 120px;" align="left">
                    <select name="BusinessCategory" class="mini-radiobuttonlist">
                        <option value="1">销货</option>
                        <option value="2">退货</option>
                    </select>
                </td>
            </tr>
        </table>
    </fieldset>
    <fieldset style="border: solid 1px #aaa; padding: 3px; height: 300px;">
        <legend>商品列表</legend>
        <div class="mini-toolbar" style="padding: 2px; border-bottom: 0;">
            <table style="width: 100%;">
                <tr>
                    <td style="width: 100%;">
                        <a class="mini-button" iconcls="icon-add" onclick="addRow();" plain="true">添加</a>
                        <a class="mini-button" iconcls="icon-remove" onclick="removeRow()" plain="true">删除</a>
                    </td>
                </tr>
            </table>
        </div>
        <!--撑满页面-->
        <div class="mini-fit">
            <div id="datagrid1" class="mini-datagrid" style="width: 100%; height: 100%;" idfield="InitPurDetailId"
                allowcelledit="true" allowcellselect="true" showfooter="false" multiselect="true"
                ondrawcell="onDrawCell" oncellcommitedit="onCellCommitEdit" allowsortcolumn="false">
                <div property="columns">
                    <div type="checkcolumn">
                    </div>
                    <div field="GoodsId" width="90" displayfield="GoodsCode" headeralign="center" allowsort="false">
                        商品编号
                    </div>
                    <div field="GoodsName" width="90" headeralign="center" allowsort="false">
                        商品名称
                    </div>
                    <div field="UnitName" width="70" headeralign="center" allowsort="false">
                        单位
                    </div>
                    <div field="Qty" name="Qty" width="80" headeralign="center" allowsort="false">
                        数量
                        <input property="editor" class="mini-spinner" minvalue="0" maxvalue="999999999" decimalplaces="4"
                            style="width: 100%;" />
                    </div>
                    <div field="SalesPrice" width="90" headeralign="center" allowsort="false">
                        销售单价
                        <input property="editor" class="mini-spinner" minvalue="0" maxvalue="999999999" decimalplaces="4"
                            style="width: 100%;" />
                    </div>
                    <div field="DiscountRate" width="90" headeralign="center" allowsort="false">
                        折扣率(%)
                        <input property="editor" class="mini-spinner" minvalue="0" maxvalue="100" decimalplaces="4"
                            style="width: 100%;" />
                    </div>
                    <div field="DeductionAmount" width="90" headeralign="center" allowsort="false">
                        折扣额
                    </div>
                    <div field="SalesAmount" width="100" headeralign="center" allowsort="false">
                        销售金额
                    </div>
                    <div field="StorageId" width="100" displayfield="StorageName" headeralign="center"
                        allowsort="false">
                        仓库
                        <input property="editor" class="mini-combobox" style="width: 100%;" valuefield="StorageId"
                            onvaluechanged="onStorageIdChanged" textfield="StorageName" url="../../Service/SetManageHandler.ashx?action=GetStorageListByCombobox" />
                    </div>
                    <div field="Remark" width="120" headeralign="center" allowsort="false">
                        备注
                        <input property="editor" class="mini-textarea" style="width: 100%;" />
                    </div>
                </div>
            </div>
        </div>
    </fieldset>
    <table style="width: 100%;">
        <tr>
            <td style="width: 12%;" align="right">
                备注：
            </td>
            <td style="width: 88%" align="left" colspan="5">
                <input name="Remark" class="mini-textarea" style="width: 100%; height: 50px;" />
            </td>
        </tr>
        <tr>
            <td style="width: 80px;" align="right">
                折扣率：
            </td>
            <td style="width: 120px;" align="left">
                <input name="DiscountRate" id="DiscountRate" class="mini-spinner" style="width: 120px;"
                    minvalue="0" maxvalue="100" decimalplaces="2" minheight="100" onvaluechanged="onDiscountRateChanged" />
            </td>
            <td style="width: 80px;" align="right">
                折扣额：
            </td>
            <td style="width: 120px;" align="left">
                <input name="DeductionAmount" id="DeductionAmount" class="mini-spinner" style="width: 120px;"
                    minvalue="0" maxvalue="999999999" decimalplaces="4" minheight="100" />
            </td>
            <td style="width: 80px;" align="right">
                折后金额：
            </td>
            <td style="width: 120px;" align="left">
                <input name="FoldAmount" id="FoldAmount" class="mini-spinner" style="width: 120px;"
                    minvalue="0" maxvalue="999999999" decimalplaces="4" minheight="100" />
            </td>
        </tr>
        <tr>
            <td style="width: 80px;" align="right">
                本次退款：
            </td>
            <td style="width: 120px;" align="left">
                <input name="Payment" id="Payment" class="mini-spinner" style="width: 120px;" minvalue="0"
                    maxvalue="999999999" decimalplaces="4" minheight="100" onvaluechanged="onPaymentChanged" />
            </td>
            <td style="width: 80px;" align="right">
                结算账户：
            </td>
            <td style="width: 120px;" align="left">
                <input name="AccountId" class="mini-combobox" style="width: 120px;" valuefield="AccountId"
                    textfield="AccountName" required="true" />
            </td>
            <td style="width: 80px;" align="right">
                本次欠款：
            </td>
            <td style="width: 120px;" align="left">
                <input name="Arrears" id="Arrears" class="mini-spinner" style="width: 120px;" minvalue="0"
                    maxvalue="999999999" decimalplaces="4" minheight="100" />
            </td>
        </tr>
    </table>
    <div style="text-align: center; padding: 10px;">
        <a class="mini-button" iconcls="icon-save" onclick="onOk" style="width: 60px; margin-right: 20px;">
            保存</a> <a class="mini-button" iconcls="icon-cancel" onclick="onCancel" style="width: 60px;">
                取消</a>
    </div>
    </form>
    <script type="text/javascript">
        mini.parse();
        mini.getbyName("BusinessCategory").setValue("1");
        var VendorId = mini.getbyName("VendorId");
        var AccountId = mini.getbyName("AccountId");
        VendorId.setUrl("../Service/SetManageHandler.ashx?action=GetVendorListByCombobox");
        AccountId.setUrl("../Service/SetManageHandler.ashx?action=GetAccountListByCombobox");
        var action;

        var grid = mini.get("datagrid1");
        var form = new mini.Form("form1");
        //提交单元格编辑数据前激发
        function onCellCommitEdit(e) {
            var editor = e.editor;
            editor.validate();
            if (editor.isValid() == false) {
                alert(editor.getErrorText());
                e.cancel = true;
            }
        }
        function onStorageIdChanged(e) {
            var combo = e.sender;
            var row = grid.getEditorOwnerRow(combo);
            var editor = grid.getCellEditor("Qty", row);
            var id = combo.getValue();
            var BusinessCategory = mini.getbyName("BusinessCategory").getValue();
            if (BusinessCategory == "2") {
                var resultQty = 0;
                $.ajax({
                    url: "../service/InitPurManageHandler.ashx?action=GetTotalInitialNumber&GoodsId=" + row.GoodsId + "&StorageId=" + e.value,
                    cache: false,
                    async: false,
                    success: function (text) {
                        resultQty = text;
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseText);
                    }
                });
                if (row.Qty > resultQty) {
                    editor.setValue(resultQty);
                    row.Qty = resultQty;
                    mini.alert("商品：" + row.GoodsCode + " " + row.GoodsName + "在仓库：" + row.StorageName + "库存不足！");
                }
            }
        }


        function onDrawCell(e) {
            var data = grid.getData();
            var record = e.record;
            var qty = record.Qty;
            var SalesPrice = record.SalesPrice;
            var discountRate = record.DiscountRate / 100;
            if (e.field == "DeductionAmount") {
                var DeductionAmount = 0;
                if (discountRate != undefined) {
                    DeductionAmount = qty * SalesPrice * discountRate;
                }
                if (isNaN(DeductionAmount)) {
                    e.cellHtml = 0;
                    e.value = 0;
                    e.row.DeductionAmount = 0;
                    record.DeductionAmount = 0;
                }
                else {
                    e.cellHtml = DeductionAmount.toFixed(4);
                    record.DeductionAmount = DeductionAmount.toFixed(4);
                }
            }
            if (e.field == "SalesAmount") {
                var SalesAmount = (qty * SalesPrice) - ((qty * SalesPrice) * discountRate);
                if (isNaN(SalesAmount)) {
                    e.cellHtml = 0;
                    e.value = 0;
                    e.row.SalesAmount = 0;
                    record.SalesAmount = 0;
                }
                else {
                    e.cellHtml = SalesAmount.toFixed(4);
                    record.SalesAmount = SalesAmount.toFixed(4);
                }
            }
            if (e.field == "Qty") {
                var BusinessCategory = mini.getbyName("BusinessCategory").getValue();
                if (BusinessCategory == "2") {
                    var resultQty = 0;
                    $.ajax({
                        url: "../service/InitPurManageHandler.ashx?action=GetTotalInitialNumber&GoodsId=" + record.GoodsId + "&StorageId=" + record.StorageId,
                        cache: false,
                        async: false,
                        success: function (result) {
                            resultQty = result;
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert(jqXHR.responseText);
                        }
                    });
                    if (e.value > resultQty) {
                        e.cellHtml = resultQty;
                        e.value = resultQty;
                        e.row.Qty = resultQty;
                        record.Qty = resultQty;
                        mini.alert("商品：" + record.GoodsCode + " " + record.GoodsName + "在仓库：" + record.StorageName + "库存不足！");
                    }
                }
            }
            if (data.length > 0) {
                var totalPrice = 0;
                var totalSalesAmount = 0;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].DiscountRate != undefined) {
                        var DeductionAmount = data[i].Qty * data[i].SalesPrice;
                        var SalesAmount = data[i].Qty * data[i].SalesPrice * (data[i].DiscountRate / 100);
                        totalPrice = DeductionAmount - SalesAmount;
                        totalSalesAmount += totalPrice;
                    }
                }
                if (isNaN(totalSalesAmount)) {
                    mini.get("FoldAmount").setValue(0);
                    mini.get("Arrears").setValue(0);
                }
                else {
                    var disRate = mini.get("DiscountRate").getValue();
                    var payment = mini.get("Payment").getValue();
                    if (disRate != 0) {
                        var DeductionAmount = totalSalesAmount * (disRate / 100);
                        mini.get("DeductionAmount").setValue(DeductionAmount);
                        mini.get("FoldAmount").setValue(totalSalesAmount - DeductionAmount);
                    }
                    else {
                        mini.get("DeductionAmount").setValue(0);
                        mini.get("FoldAmount").setValue(totalSalesAmount);
                        mini.get("Arrears").setValue(totalSalesAmount);
                    }
                }
            }
        }

        function onDiscountRateChanged(e) {
            var data = grid.getData();
            var disRate = e.value;
            var Payment = mini.get("Payment").getValue();
            var totalSalesAmount = 0;
            for (var i = 0; i < data.length; i++) {
                if (data[i].DiscountRate != undefined) {
                    var DeductionAmount = data[i].Qty * data[i].SalesPrice;
                    var SalesAmount = data[i].Qty * data[i].SalesPrice * (data[i].DiscountRate / 100);
                    totalPrice = DeductionAmount - SalesAmount;
                    totalSalesAmount += totalPrice;
                }
            }
            if (e.value != 0) {
                var DeductionAmount = totalSalesAmount * (disRate / 100);
                var price = totalSalesAmount - DeductionAmount;
                mini.get("DeductionAmount").setValue(DeductionAmount);
                mini.get("FoldAmount").setValue(price);
                mini.get("Arrears").setValue(price - Payment);
            }
            else {
                mini.get("DeductionAmount").setValue(0);
                mini.get("FoldAmount").setValue(totalSalesAmount);
                mini.get("Arrears").setValue(totalSalesAmount - Payment);
            }
        }

        function onPaymentChanged(e) {
            var FoldAmount = mini.get("FoldAmount").getValue();
            if (e.value != 0) {
                var arrears = FoldAmount - e.value;
                mini.get("Arrears").setValue(arrears);
            }
            else {
                mini.get("Arrears").setValue(FoldAmount);
            }
        }

        function addRow() {
            mini.open({
                url: "CommForm/SelectGoodsWindow.aspx",
                title: "选择商品", width: 650, height: 495,
                ondestroy: function (action) {
                    if (action == "ok") {
                        var iframe = this.getIFrameEl();
                        var data = iframe.contentWindow.GetData();
                        data = mini.clone(data);    //必须
                        if (data) {
                            //                            var idMaps = {};
                            //                            var datas = grid.getData();
                            //                            for (var i = 0, l = datas.length; i < l; i++) {
                            //                                var o = datas[i];
                            //                                var id = o["GoodsId"];
                            //                                idMaps[id] = o;
                            //                            }
                            //                            if (datas.length > 0) {
                            //                                for (var i = data.length - 1; i >= 0; i--) {
                            //                                    var o = data[i];
                            //                                    var id = o["GoodsId"];
                            //                                    if (idMaps[id] != null) data.removeAt(i);
                            //                                }
                            //                            }
                            grid.addRows(data);
                        }
                    }
                }
            });
        }
        function removeRow() {
            var rows = grid.getSelecteds();
            if (rows.length > 0) {
                grid.removeRows(rows, true);
            }
        }
        function SaveData() {
            var data = grid.getData();
            var o = form.getData();
            o.SaleNumber = $("#SaleNumber")[0].innerHTML;
            form.validate();
            if (form.isValid() == false) return;
            if (data.length > 0) {
                var GoodsIdCount = 0;
                var StorageIdCount = 0;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].GoodsId == undefined) {
                        GoodsIdCount = GoodsIdCount + 1;
                    }
                    if (data[i].StorageId == undefined) {
                        StorageIdCount = StorageIdCount + 1;
                    }
                }
                if (GoodsIdCount > 0) {
                    mini.alert("商品不能为空，请重新选择...");
                    return;
                }
                if (StorageIdCount > 0) {
                    mini.alert("仓库不能为空，请重新选择...");
                    return;
                }
                saveData(o, data);
            }
            else {
                mini.alert("商品列表不能为空！");
            }
        }
        function saveData(o, data) {
            o.arrList = data;
            var json = mini.encode([o]);
            if (viewaction == "edit") {
                $.ajax({
                    url: "../Service/InitPurManageHandler.ashx?action=ModifyInitPur",
                    data: { data: json },
                    type: 'POST',
                    success: function (text) {
                        CloseWindow("save");
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseText);
                    }
                });
            }
            else {
                $.ajax({
                    url: "../Service/InitPurManageHandler.ashx?action=AddInitPur",
                    data: { data: json },
                    type: 'POST',
                    success: function (text) {
                        CloseWindow("save");
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseText);
                    }
                });
            }
        }

        function SetData(data) {
            viewaction = data.action;
            data = mini.clone(data);
            //mini.getbyName("SaleNumber").setEnabled(false);
            mini.get("FoldAmount").setEnabled(false);
            mini.get("Arrears").setEnabled(false);
            if (data.action == "edit") {
                $.ajax({
                    url: "../service/InitPurManageHandler.ashx?action=GetInitPurInfo&InitPurId=" + data.InitPurId,
                    cache: false,
                    success: function (text) {
                        var o = mini.decode(text);
                        form.setData(o);
                        form.setChanged(false);
                        $("#SaleNumber").text(o.SaleNumber);
                        $.ajax({
                            url: "../service/InitPurManageHandler.ashx?action=GetInitPurDetailList&InitPurId=" + data.InitPurId,
                            cache: false,
                            success: function (text) {
                                var o = mini.decode(text);
                                grid.setData(o);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                alert(jqXHR.responseText);
                            }
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseText);
                    }
                });
            }
            else {
                mini.getbyName("DocDate").setValue(new Date().format("yyyy-MM-dd"));
                $.ajax({
                    url: "../service/CommonManageHandler.ashx?action=GetSaleNumber",
                    success: function (text) {
                        $("#SaleNumber").text(text);
                        //mini.getbyName("SaleNumber").setValue(text);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseText);
                    }
                });
            }
        }
        function GetData() {
            var o = form.getData();
            return o;
        }
        function CloseWindow(action) {
            if (action == "close" && form.isChanged()) {
                if (confirm("数据被修改了，是否先保存？")) {
                    return false;
                }
            }
            if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
            else window.close();
        }

        function onOk() {
            SaveData();
        }
        function onCancel(e) {
            CloseWindow("cancel");
        }
    </script>
</body>
</html>
